// ignore_for_file: dangling_library_doc_comments, slash_for_doc_comments
/*** 
 * @Author: Zhong
 * @Date: 2025-03-07 16:11:05
 * @LastEditors: Zhong zhongxiaodong@eenet.com
 * @LastEditTime: 2025-08-21 17:01:39
 * @FilePath: /wan_android_flutter/lib/module_code/home/pages/home_page.dart
 * @Description: 
 */

import 'dart:math';

import 'package:flutter/material.dart' hide Size;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:skeletonizer/skeletonizer.dart';
import 'package:wan_android_flutter/common_code/configs/app_color_config.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:wan_android_flutter/common_code/pages/common_webview.dart';
import 'package:wan_android_flutter/module_code/home/models/home_tab_classify_model.dart';

import '../../../common_code/configs/app_config.dart';
import '../../../common_code/widgets/custom_sliver_header_delegate.dart';
import '../api/home_api.dart';
import '../models/home_banner_model.dart';
import '../models/home_tab_list_model.dart';
import '../widgets/home_page_cell.dart';

class HomePage extends StatefulWidget {
  static const String routeName = '/home_tab';
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  //Controller
  late ScrollController _scrollController;
  late TabController _tabController;
  late PageController _pageController;

  double _appBarOpacity = 0.0; // 导航栏透明度
  final double _expandedHeight = 200.0.w; // AppBar展开高度

  // 轮播图数据
  List<HomeBannerDataModel> homeBannerList = [];
  // tab分类数据
  List<HomeTabClassifyDataModel> homeTabClassifyList = [];

  // 是否显示骨架屏
  bool showSwiperSkeleton = true;
  bool showTabBarSkeleton = true;

  @override
  void initState() {
    super.initState();

    // 配置骨架屏数据
    configSkeletonData();

    _tabController = TabController(
      length: homeTabClassifyList.length,
      vsync: this,
    );

    _pageController = PageController(
      initialPage: 0,
      keepPage: true, //保持当前页面，待验证
    );

    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        _pageController.animateToPage(
          _tabController.index,
          duration: Duration(milliseconds: 300),
          curve: Curves.ease,
        );
      }
    });

    //滚动监听，用来设置标题显示与隐藏
    _scrollController = ScrollController()
      ..addListener(() {
        // 计算导航栏透明度（根据滚动位置）
        final double offset = _scrollController.offset;
        if (offset <= 0) {
          // 完全展开时（滚动到顶部）
          _appBarOpacity = 0.0;
        } else if (offset >= _expandedHeight - kToolbarHeight) {
          // 完全收起时
          _appBarOpacity = 1.0;
        } else {
          // 中间过渡状态
          _appBarOpacity = offset / (_expandedHeight - kToolbarHeight);
        }
        setState(() {}); // 更新UI
      });

    // 获取Swiper数据
    HomeApi.getHomeBanner().then((value) {
      debugPrint(value.toString());
      setState(() {
        homeBannerList = value ?? [];
        showSwiperSkeleton = false;
      });
    });

    // 获取tab分类数据
    HomeApi.getHomeTabData().then((value) {
      debugPrint(value.toString());
      setState(() {
        homeTabClassifyList = value ?? [];
        _tabController = TabController(
          length: homeTabClassifyList.length,
          vsync: this,
        );
        showTabBarSkeleton = false;
      });
    });
  }

  @override
  void dispose() {
    //销毁Controller
    _scrollController.dispose();
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        controller: _scrollController,
        headerSliverBuilder: (context, innerBoxIsScrolled) {
          return [
            // 计算重叠量
            SliverOverlapAbsorber(
              handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
              sliver: SliverAppBar(
                title: _buildAnimatedTitle(),
                pinned: true,
                expandedHeight: _expandedHeight + 40,
                flexibleSpace: FlexibleSpaceBar(
                  background: Container(
                    padding: EdgeInsets.only(bottom: 40),
                    color: AppColorConfig.backgroundColor,
                    child: _buildDotsBarSwiper(context),
                  ),
                ),
                bottom: PreferredSize(
                  preferredSize: Size(double.infinity, 40),
                  child: Container(
                    color: Colors.white,
                    width: double.infinity,
                    child: _buildTabBar(context),
                  ),
                ),
              ),
            ),

            // 吸顶头部
            // SliverPersistentHeader(
            //   delegate: CustomSliverHeaderDelegate(
            //     minHeight: 40,
            //     maxHeight: 40,
            //     child: Container(
            //       color: Colors.white,
            //       width: double.infinity,
            //       child: _buildTabBar(context),
            //     ),
            //   ),
            //   pinned: true,
            // ),
          ];
        },
        body: Container(
          color: AppColorConfig.backgroundColor,
          child: PageView.builder(
            controller: _pageController,
            onPageChanged: (index) {
              _tabController.animateTo(index);
            },
            itemBuilder: (context, index) {
              return HomeTabBarContent(cid: homeTabClassifyList[index].id ?? 0);
            },
          ),
          // PageView(
          //   controller: _pageController,
          //   onPageChanged: (index) {
          //     _tabController.animateTo(index);
          //   },
          //   children: homeTabClassifyList.map((e) {
          //     return HomeTabBarContent(cid: e.id!);
          //   }).toList(),
          // ),
        ),
        // body: Container(
        //   color: AppColorConfig.backgroundColor,
        //   child: TabBarView(
        //     controller: _tabController,
        //     children: homeTabClassifyList.map((e) {
        //       return HomeTabBarContent(
        //         keepAliveKey: "${e.id}",
        //         cid: e.id!,
        //         key: PageStorageKey(e.id),
        //       );
        //     }).toList(),
        //   ),
        // ),
      ),
    );
  }

  // 配置骨架屏数据
  void configSkeletonData() {
    // 轮播图数据
    for (var i = 0; i < 3; i++) {
      HomeBannerDataModel bannerDataModel = HomeBannerDataModel();
      bannerDataModel.imagePath =
          "https://picsum.photos/250?image=${Random().nextInt(1000)}";
      homeBannerList.add(bannerDataModel);
    }

    // 分类数据
    for (var i = 0; i < 10; i++) {
      HomeTabClassifyDataModel classifyDataModel = HomeTabClassifyDataModel();
      classifyDataModel.name = "111111";
      classifyDataModel.id = 1;
      homeTabClassifyList.add(classifyDataModel);
    }
  }

  // 构建随透明度变化的标题
  Widget _buildAnimatedTitle() {
    return AnimatedOpacity(
      opacity: _appBarOpacity, // 根据导航栏透明度变化
      duration: const Duration(milliseconds: 200), // 过渡动画时长
      curve: Curves.easeInOut, // 动画曲线
      child: const Text(
        '首页',
        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
      ),
    );
  }

  // 构建轮播图
  Widget _buildDotsBarSwiper(BuildContext context) {
    if (homeBannerList.isNotEmpty) {
      return Skeletonizer(
        enabled: showSwiperSkeleton,
        enableSwitchAnimation: true,
        child: Swiper(
          autoplay: true,
          itemCount: homeBannerList.length,
          loop: true,
          pagination: const SwiperPagination(
            alignment: Alignment.bottomCenter,
            builder: TDSwiperDotsPagination(
              roundedRectangleWidth: 20,
              color: Colors.grey,
              activeColor: AppColorConfig.themeColor,
            ),
          ),
          itemBuilder: (BuildContext context, int index) {
            return FadeInImage.assetNetwork(
              placeholder: "${AppConfig.imgPath}empty.png",
              image: homeBannerList[index].imagePath ?? "",
              fit: BoxFit.cover,
            );
          },
          onTap: (index) {
            Get.toNamed(CommonWebview.routeName, arguments: {"url": homeBannerList[index].url ?? ""});
          },
        ),
      );
    } else {
      return Container(
        height: 200,
        color: AppColorConfig.backgroundColor,
        child: Center(child: Text("暂无数据")),
      );
    }
  }

  // 构建TabBar
  Widget _buildTabBar(BuildContext context) {
    return Skeletonizer(
      enabled: showTabBarSkeleton,
      enableSwitchAnimation: true,
      child: TabBar(
        controller: _tabController,
        isScrollable: true,
        tabAlignment: TabAlignment.start,
        indicatorColor: AppColorConfig.themeColor,
        labelColor: AppColorConfig.themeColor,
        labelStyle: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold),
        unselectedLabelStyle: TextStyle(
          fontSize: 16.0.sp,
          fontWeight: FontWeight.w600,
        ),
        tabs: homeTabClassifyList.map((e) {
          return Tab(text: e.name);
        }).toList(),
        onTap: (index) {
          _pageController.animateToPage(
            index,
            duration: Duration(milliseconds: 300),
            curve: Curves.ease,
          );
        },
      ),
    );
  }
}

//内容列表
class HomeTabBarContent extends StatefulWidget {
  const HomeTabBarContent({required this.cid});

  final int cid;

  @override
  State<HomeTabBarContent> createState() => _HomeTabBarContentState();
}

class _HomeTabBarContentState extends State<HomeTabBarContent>
    with AutomaticKeepAliveClientMixin {
  List<HomeTabListDataDataModel> _homeArticleList = [];

  // 是否显示骨架屏
  bool showListSkeleton = true;

  @override
  void initState() {
    super.initState();

    // 配置骨架屏数据
    configSkeletonData();

    // 获取列表数据
    HomeApi.getHomeTabListData(cid: widget.cid).then((value) {
      if (value != null) {
        setState(() {
          _homeArticleList = value;
          showListSkeleton = false;
        });
      }
    });
  }

  @override
  void dispose() {
    debugPrint('Tab ${widget.key} DISPOSE'); // 调试日志
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Skeletonizer(
      enabled: showListSkeleton,
      enableSwitchAnimation: true,
      child: CustomScrollView(
        slivers: [
          // 占位
          SliverOverlapInjector(
            handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
          ),
          SliverPadding(
            padding: EdgeInsets.all(8),
            sliver: SliverList.builder(
              itemBuilder: (context, index) {
                return HomePageCell(model: _homeArticleList[index]);
              },
              itemCount: _homeArticleList.length,
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  // 配置骨架屏数据
  void configSkeletonData() {
    // 列表数据
    for (var i = 0; i < 6; i++) {
      HomeTabListDataDataModel model = HomeTabListDataDataModel();
      model.title = "测试标题 $i";
      model.desc = "测试描述 $i";
      model.author = "测试作者 $i";
      model.chapterName = "测试章节 $i";
      model.superChapterName = "测试章节 $i";
      model.publishTime = 123456;
      model.envelopePic = "https://picsum.photos/id/60/80/";
      _homeArticleList.add(model);
    }
  }
}
